﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PivotTombstoner.cs" company="XamlNinja">
//   2011 Richard Griffin and Ollie Riches
// </copyright>
// <summary>
//   Pivot Tombstoner.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace WP7Contrib.View.Controls.Tombstoner
{
    using System;
    using System.Windows.Controls;

    using Microsoft.Phone.Controls;

    public sealed class PivotTombstoner : ICanTombstone
    {
        public Type ControlType
        {
            get { return typeof(Pivot); }
        }

        public void Persist<T>(T control, PhoneApplicationPage page) where T : Control
        {
            if (!(control is Pivot))
            {
                return;
            }

            if (string.IsNullOrEmpty(control.Name))
            {
                return;
            }

            try
            {
                var pivot = control as Pivot;
                if (pivot.SelectedIndex > 0)
                {
                    page.State.Add(string.Format("Pivot^{0}", pivot.Name), pivot.SelectedIndex);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

        public void Restore<T>(T control, PhoneApplicationPage page) where T : Control
        {
            if (!(control is Pivot))
            {
                return;
            }

            if (string.IsNullOrEmpty(control.Name))
            {
                return;
            }

            object value;
            var key = string.Format("Pivot^{0}", control.Name);
            if (!page.State.TryGetValue(key, out value))
            {
                return;
            }

            RenderScheduler.ScheduleOnNextRender(() =>
            {
                try
                {
                    if (page.State.TryGetValue(key, out value))
                    {
                        (control as Pivot).SelectedIndex = (int)value;
                        page.State.Remove(key);
                    }
                }
                catch (Exception)
                {
                }
            });
        }
    }
}
